package org.squabble.web.account;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.squabble.SquabbleConstants;
import org.squabble.service.AccountService;
import org.squabble.service.LoginService;

@Controller
@RequestMapping("/account/reset")
public class PasswordResetController {

	protected final Log logger = LogFactory.getLog(getClass());

	@Autowired
	@Qualifier("validator")
	Validator validator;

	@Autowired
	LoginService loginService;

	@Autowired
	AccountService accountService;

	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(
			@RequestParam(value = "validationCode", required = false) String validationCode,
			ModelMap model, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		PasswordResetCommand prc = new PasswordResetCommand();
		if (StringUtils.isNotBlank(validationCode)) {
			if (accountService.validationCodeExists(validationCode)) {
				accountService.doPasswordResetEmail(validationCode, request
						.getRemoteAddr());
				model.addAttribute(SquabbleConstants.POST_PROCESS_MESSAGE,
						"reset.processed[1]");
				return "redirect:/account/login";
			}
		}
		model.addAttribute("passwordResetCommand", prc);
		return "account.reset";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(ModelMap map,
			@ModelAttribute("passwordResetCommand") PasswordResetCommand prc,
			BindingResult result, HttpServletRequest request) throws Exception {
		validator.validate(prc, result);
		if (result.hasErrors()) {
			return "account.reset";
		}
		if (StringUtils.isBlank(prc.getValidationCode())) {
			accountService.doValidationEmail(prc.getEmail(), request
					.getRemoteAddr());
			map.addAttribute(SquabbleConstants.POST_PROCESS_MESSAGE,
					"reset.processed[0]");
		} else {
			accountService.doPasswordResetEmail(prc.getValidationCode(),
					request.getRemoteAddr());
			map.addAttribute(SquabbleConstants.POST_PROCESS_MESSAGE,
					"reset.processed[1]");
		}

		return "redirect:/account/login";
	}

}
